<script lang="ts" setup>
import type { CreateTemplateForm } from "../configs/dialogConfigs"
import { createTemplateDialogConfig } from "../configs/dialogConfigs"

interface Props {
  modelValue: boolean
  user?: any
  mode?: "create" | "edit"
  initialData?: Partial<CreateTemplateForm>
}

interface Emits {
  (e: "update:modelValue", value: boolean): void
  (e: "success", template: CreateTemplateForm): void
}

const props = withDefaults(defineProps<Props>(), {
  user: undefined,
  mode: "create"
})

const emit = defineEmits<Emits>()

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit("update:modelValue", value)
})

// 表单引用
const formRef = ref()

// 表单数据（默认套餐为 Pro版）
const formData = reactive<CreateTemplateForm>({
  name: "",
  platform: "",
  workflowId: "",
  version: "Pro版"
})

// 动态标题与提交按钮文案
const dialogTitle = computed(() => props.mode === "edit" ? "编辑专属模板" : createTemplateDialogConfig.title)
const submitButtonText = computed(() => props.mode === "edit" ? "确定修改" : "创建模板")

// 已移除样例预览相关逻辑

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入模板名称", trigger: "blur" },
    { min: 2, max: 50, message: "长度在 2 到 50 个字符", trigger: "blur" }
  ],
  platform: [
    { required: true, message: "请选择适用平台", trigger: "change" }
  ],
  workflowId: [
    { required: true, message: "请输入工作流链路ID", trigger: "blur" },
    { min: 5, max: 100, message: "长度在 5 到 100 个字符", trigger: "blur" }
  ],
  version: [
    { required: true, message: "请选择套餐等级", trigger: "change" }
  ]
}

// 平台选项
const platformOptions = [
  { label: "抖音", value: "抖音" },
  { label: "小红书", value: "小红书" }
]

// 套餐等级选项（单选）
const versionOptions = [
  { label: "标准版", value: "标准版" },
  { label: "专业版 Pro", value: "Pro版" },
  { label: "专业版 Pro Max", value: "Pro Max版" }
]

// 重置表单
function resetForm() {
  formData.name = ""
  formData.platform = ""
  formData.workflowId = ""
  formData.version = "Pro版"
  formRef.value?.clearValidate()
}

// 当弹窗打开且为编辑模式时，回填初始数据
watch(() => props.modelValue, (visible: boolean) => {
  if (visible && props.mode === "edit" && props.initialData) {
    formData.name = props.initialData.name || ""
    formData.platform = props.initialData.platform || ""
    formData.workflowId = props.initialData.workflowId || ""
    formData.version = props.initialData.version || "Pro版"
  }
  if (visible && props.mode === "create") {
    resetForm()
  }
})

// 关闭弹窗
function handleClose() {
  resetForm()
  dialogVisible.value = false
}

// 提交表单
async function handleSubmit() {
  try {
    await formRef.value.validate()

    // 构建提交数据
    const submitData = { ...formData }

    // 发送成功事件
    emit("success", submitData)

    // 成功提示（仅在创建模式提示，编辑模式由父组件提示，避免重复）
    if (props.mode === "create") {
      ElMessage.success("模板创建成功")
    }

    // 关闭弹窗
    handleClose()
  } catch (error) {
    console.log("表单验证失败", error)
  }
}

// 已移除文件上传相关方法
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="700px"
    :before-close="handleClose"
    custom-class="create-template-dialog"
  >
    <!-- 弹窗描述 -->
    <div class="dialog-description">
      {{ createTemplateDialogConfig.description }}
    </div>

    <!-- 表单 -->
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="160px"
      class="template-form"
    >
      <!-- 模板名称 -->
      <el-form-item label="模板名称" prop="name" required>
        <el-input
          v-model="formData.name"
          :placeholder="createTemplateDialogConfig.fields[0].placeholder"
          clearable
        />
      </el-form-item>

      <!-- 适用平台 -->
      <el-form-item label="适用平台" prop="platform" required>
        <el-select
          v-model="formData.platform"
          :placeholder="createTemplateDialogConfig.fields[1].placeholder"
          style="width: 100%"
        >
          <el-option
            v-for="option in platformOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-form-item>

      <!-- 爆款工作流链路ID -->
      <el-form-item label="爆款工作流链路ID" prop="workflowId" required>
        <el-input
          v-model="formData.workflowId"
          :placeholder="createTemplateDialogConfig.fields[2].placeholder"
          clearable
        />
      </el-form-item>

      <!-- 可用套餐等级（单选，默认 Pro） -->
      <el-form-item label="可用套餐等级" prop="version" required>
        <el-radio-group v-model="formData.version">
          <el-radio
            v-for="option in versionOptions"
            :key="option.value"
            :label="option.value"
          >
            {{ option.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 已移除样例预览功能 -->
    </el-form>

    <!-- 弹窗底部按钮 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button
          type="primary"
          @click="handleSubmit"
        >
          {{ submitButtonText }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.create-template-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;

    .el-dialog__header {
      padding: 24px 24px 16px 24px;
      border-bottom: 1px solid var(--el-border-color-extra-light);

      .el-dialog__title {
        font-size: 20px;
        font-weight: 800 !important;
        color: var(--el-text-color-primary);
      }
    }

    .el-dialog__body {
      padding: 24px;
    }

    .el-dialog__footer {
      padding: 16px 24px 24px 24px;
      border-top: 1px solid var(--el-border-color-extra-light);
    }
  }
}

.dialog-description {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  line-height: 1.5;
  margin-bottom: 24px;
}

.template-form {
  .el-form-item {
    margin-bottom: 20px;

    .el-form-item__label {
      font-weight: 500;
      color: var(--el-text-color-regular);
    }

    .el-input,
    .el-select {
      .el-input__wrapper {
        border-radius: 6px;
        border: 1px solid var(--el-border-color-lighter);
        height: 40px;

        &:hover {
          border-color: var(--el-border-color);
        }

        &.is-focus {
          border-color: var(--el-color-primary);
          box-shadow: 0 0 0 2px var(--el-color-primary-light-9);
        }
      }
    }

    .el-checkbox-group {
      display: flex;
      gap: 16px;

      .el-checkbox {
        margin-right: 0;
      }
    }

    .el-upload {
      .el-upload__tip {
        color: var(--el-text-color-secondary);
        font-size: 12px;
        margin-top: 8px;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;

  .el-button {
    padding: 10px 20px;
    border-radius: 6px;
    font-weight: 500;

    &:first-child {
      border-color: var(--el-border-color);
      color: var(--el-text-color-secondary);

      &:hover {
        border-color: var(--el-border-color);
        color: var(--el-text-color-regular);
      }
    }
  }
}
</style>
